﻿using ETask.Client.ViewModels;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ETask.Client
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainViewModel();
        }

        private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void NotifyIcon_MouseDoubleClick(object sender, RoutedEventArgs e)
        {
            if (this.WindowState == WindowState.Minimized)
            {
                this.WindowState = WindowState.Normal;
            }
            else if (this.Visibility == Visibility.Hidden)
            {
                this.Visibility = Visibility.Visible;
            }
            this.Activate(); // 将窗口置于最前端并激活它
        }

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (DataContext is MainViewModel viewModel)
            {
                // 如果点击的不是DatePicker本身，则隐藏
                if (e.OriginalSource is DependencyObject source &&
                    !IsElementOrParent(source, taskDatePicker))
                {
                    viewModel.HideDatePicker();
                }
            }
        }

        private bool IsElementOrParent(DependencyObject element, DependencyObject target)
        {
            while (element != null)
            {
                if (element == target)
                    return true;
                element = VisualTreeHelper.GetParent(element);
            }
            return false;
        }

        private void taskDatePicker_SelectedDateChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            e.Handled = true;
            if (DataContext is MainViewModel viewModel)
            {
                viewModel.HideDatePicker();
            }
        }
    }
}